package com.wan37.protobuf.util;

import com.google.protobuf.Message;
import com.wan37.protobuf.analysis.ParseMap;
import com.wan37.protobuf.constant.PtoNum;
import com.wan37.protobuf.message.internal.Internal;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * 客户端使用的Protobuf消息封装工具.
 */
public class ClientProtoUtils {


    private ClientProtoUtils() {
    }


    /**
     * 将客户端将要发送的消息封装成发往服务器端的消息, 返回ByteBuf对象.
     *
     * @param sceneId
     * @param msg
     * @return
     */
    public static ByteBuf pack2Server(String sceneId, Message msg) {

        int ptoNum = ParseMap.getPtoNum(msg);
        Internal.GameToGate gameToGate = Internal.GameToGate.newBuilder()
                .setSceneId(sceneId)
                .setPtoNum(ptoNum)
                .setMsg(msg.toByteString()).build();

        byte[] bytes = gameToGate.toByteArray();
        int length = bytes.length;

        ByteBuf sendBuf = Unpooled.buffer(8 + length);
        sendBuf.writeInt(length);
        sendBuf.writeInt(PtoNum.GAMETOGATE);
        sendBuf.writeBytes(bytes);

        return sendBuf;
    }
}
